/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import sysConfig from "@/config";
import { permission } from '@/utils/permission'

const tool = {}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if (sysConfig.LS_ENCRYPTION == "AES") {
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
		let cacheValue = {
			content: data,
			datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
		}
		return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
		try {
			const value = JSON.parse(localStorage.getItem(key))
			if (value) {
				let nowTime = new Date().getTime()
				if (nowTime > value.datetime && value.datetime != 0) {
					localStorage.removeItem(key)
					return null;
				}
				//解密
				if (sysConfig.LS_ENCRYPTION == "AES") {
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
				return value.content
			}
			return null
		} catch (err) {
			return null
		}
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config = {}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if (cfg.expires) {
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if (cfg.path) {
			cookieStr += `;path=${cfg.path}`
		}
		if (cfg.domain) {
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name) {
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"))
		if (arr != null) {
			return unescape(arr[2])
		} else {
			return null
		}
	},
	remove(name) {
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if (isFull) {
		if (document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen();
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen();
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+": date.getMonth() + 1,                 //月份
		"d+": date.getDate(),                    //日
		"h+": date.getHours(),                   //小时
		"m+": date.getMinutes(),                 //分
		"s+": date.getSeconds(),                 //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if (!num.includes('.')) {
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data) {
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data) {
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher) {
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config = {}) {
			if (secretKey.length % 8 != 0) {
				console.warn("[SCUI error]: 秘钥长度需为8的倍数，否则解密将会失败。")
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config = {}) {
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
},


/* 非按钮权限验证是否显示 */
tool.auth = {
	/**
	 * 非按钮权限验证是否显示
	 */
	verification(value) {
		if(Array.isArray(value)){
			let ishas = false;
			value.forEach(item => {
				if(permission(item)){
					ishas = true;
				}
			})
			return ishas
		}else {
			if(permission(value)){
				return true;
			}
		}
		return false
	},

	/**
	 * 设置操作列宽度 (支持二维数据， 如果子级为数据， 默认为 一组权限只要满足一个权限，默认按钮显示)
	 * @param vals 权限标识 数组类型
	 * @returns {number} 列宽
	 */
	setTableOperationWidth(val) {
		let width = 0;
		let incremental = 67;
		if (Array.isArray(val)) {
			val.forEach(item => {
				width += tool.auth.verification(item) ? incremental : 0;
			})
		} else {
			width += tool.auth.verification(val) ? incremental : 0;
		}
		width += width == incremental ? 23 : 0;
		return width;
	}
}

/* 菜单页面中尺寸 */
tool.page = {

	/**
	 * 菜单页面中 <el-header :height="headerHeight">...</el-header> 头部查询条件和新增编辑按钮区域高度
	 */
	updateHeight(height = 54) {
		let colWidth = 304;
		let items = document.getElementsByTagName("header")

		// 验证是否包含 操作按钮 如何新增、批量删除
		let operation = false
		for (let child of items) {
			if(!child){
				continue
			}
			let childrens = child.children;
			if(!childrens){
				continue
			}
			for (let childSub of childrens) {
				if(childSub.id == "operation"){
					operation = true;
					break;
				}
			}
		}

		for (let item of items) {
			if (item.className == 'el-header') {
				height = operation ? height : 8;

				let offsetWidth = item.offsetWidth;
				let n = parseInt(offsetWidth / colWidth);
				let num = item.getElementsByClassName("el-form-item");
				if(num.length == 0 && operation == false){
					let page = document.getElementById("adminui-main");
					try {
						if (page != undefined) {
							page.getElementsByClassName("el-header")[0].remove();
						}
					} catch (e) {
						console.log(e);
					}
					return 0 + 'px';
				}
				let res = parseInt(num.length / n);
				let remainder = num.length % n;
				if (remainder > 0) {
					res++;
				}
				height += res * 50;
				break
			}
		}
		return height + 'px';
	},
}

/* Number类型数据运算 */
tool.number = {

	add(arg1, arg2) { // 浮点型加法
		arg1 = Number(arg1)
		arg2 = Number(arg2)
		var r1, r2, m, n;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2))
		n = (r1 >= r2) ? r1 : r2;
		return ((arg1 * m + arg2 * m) / m).toFixed(n);
	},

	subtract(arg1, arg2) { // 浮点型减法
		var re1, re2, m, n;
		try {
			re1 = arg1.toString().split(".")[1].length;
		} catch (e) {
			re1 = 0;
		}
		try {
			re2 = arg2.toString().split(".")[1].length;
		} catch (e) {
			re2 = 0;
		}
		m = Math.pow(10, Math.max(re1, re2));
		n = (re1 >= re2) ? re1 : re2;
		return ((arg1 * m - arg2 * m) / m).toFixed(n);
	},

	multiply(arg1, arg2) { // 浮点型乘法
		var m = 0;
		var s1 = arg1.toString();
		var s2 = arg2.toString();
		try {
			if(s1.toString().indexOf(".") != -1){
				m += s1.split(".")[1].length;
			}
		} catch (e) {
			console.log(e)
		}
		try {
			if(s2.toString().indexOf(".") != -1){
				m += s2.split(".")[1].length;
			}
		} catch (e) {
			console.log(e)
		}
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
	},

	checkNumberData(data, num) {  // 检查number类型并保留小数长度  返回的结果 不合法返回 ''
		data = (data == undefined || data == '') ? Number(0).toFixed(num) : Number(data).toFixed(num);
		return isNaN(data) ? '' : (Number(data) >= 0 ? data : '');
	},

	checkNumberDataNotEmpty(data, num) {  // 检查number类型并保留小数长度  返回的结果 不合法返回 0.00
		data = (data == undefined || data == '') ? Number(0).toFixed(num) : Number(data).toFixed(num);
		return isNaN(data) ? Number(0).toFixed(num) : (Number(data) >= 0 ? data : Number(0).toFixed(num));
	},

	divide(arg1, arg2, digit) { // 除数，被除数， 保留的小数点后的位数
		var t1 = 0,
			t2 = 0,
			r1, r2;
		try {
			if(arg1.toString().indexOf(".") != -1){
				t1 = arg1.toString().split(".")[1].length
			}
		} catch (e) {
			console.log("错误：arg1 = " + arg1 + "， arg2 = "+ arg2 + "，" +e)
		}
		try {
			if(arg2.toString().indexOf(".") != -1){
				arg2 = arg2.toString().split(".")[1].length
			}
		} catch (e) {
			console.log("错误：arg1 = " + arg1 + "， arg2 = "+ arg2 + "，" +e)
		}
		r1 = Number(arg1.toString().replace(".", ""))
		r2 = Number(arg2.toString().replace(".", ""))
		//获取小数点后的计算值
		var result = ((r1 / r2) * Math.pow(10, t2 - t1)).toString()
		var result2 = result.split(".")[1];
		if (result2 == undefined) {
			result2 = '0'
		}
		result2 = result2.substring(0, digit > result2.length ? result2.length : digit);
		return Number(result.split(".")[0] + "." + result2);
	}
}


export default tool
